<?
//==================================결제모듈 관련(데이콤)=========================================
function write_success($value)
{
	$oid_find_sql = "select idx from g4_PG_dacom where oid='".$value[oid]."'";
	$oid_find = mysql_num_rows(mysql_query($oid_find_sql));
	if($oid_find)
	{
		return true;
	}
	else
	{
		$qry_pre = "INSERT INTO g4_PG_dacom(";
		$qry_post = " VALUES(";
		reset($value);
		while(list($key, $val) = each($value))
		{
			$qry_pre.= $key.",";
			$qry_post.= "'".addslashes($val)."',";
		}
		$qry_pre.= "datetime";	// 자료수신일자 기록용 필드 추가
		$qry_post.= "now()";	// 자료수신일자 : 데이터 수신시점
		$qry = $qry_pre.")".$qry_post.")";

		if( !(mysql_query($qry)) )	// DB처리 에러 발생시
		{
			//DB저장 불가시에는 파일로 별도 기록하여 DB 입력에러 사유를 확인토록 함
			$body = "[".date("Y-m-d :h:i:s A")."] 결제성공 (oid : ".$value[oid].") ".$qry;
			write_log("./write_failure.log",$body);
			return false;	// DB처리에 대한 결과 반환
		}
		else
		{

			$order_row = mysql_fetch_array(mysql_query("select * from g4_order where oid = '".$value[oid]."' limit 1"));

			$tmp_status_history = explode("/",$order_row[status_history]);

			$tmp_status_history[] = "2|".date("Y-m-d H:i:s");

			$status_history = implode("/",$tmp_status_history);

			if($value[msgtype] == "GMC")
			{
				$pay_info = "승인번호:".$value[authnumber]."|카드번호:".$value[cardnumber]."|유효기간:".$value[cardexp]."|할부개월수:".$value[cardperiod]."|무이자:".$value[nointerestflag];
			}
			elseif($value[msgtype] == "BMC")
			{
				$pay_info = "계좌번호:".$value[accountnumber]."|계좌소유주:".$value[accountowner]."|계좌주민번호:".$value[pid];
			}
			elseif($value[msgtype] == "WMC")
			{
				$pay_info = "휴대폰번호:".$value[telno]."|명의자주민번호:".$value[pid];
			}
			else
			{
				$pay_info = "입금할계좌:".$value[accountnumber]."|입금총액:".$value[tamount];
			}

			$sql2 = "update g4_order set status = '2', status_history = '".$status_history."',pay_info='".$pay_info."'  where oid = '".$value[oid]."' limit 1";

			$rst2 = mysql_query($sql2);


			if($rst2)
			{
				write_log("./write_success.log", $value);
				return true;
			}
			else
			{
				write_log("./write_failure.log", $value);
				return false;
			}

		}
	}
}


function write_failure($value)
{
	$oid_find_sql = "select idx from g4_PG_dacom where oid='".$value[oid]."'";
	$oid_find = mysql_num_rows(mysql_query($oid_find_sql));
	if($oid_find)
	{
		return true;
	}
	else
	{
		$qry_pre = "INSERT INTO g4_PG_dacom(";
		$qry_post = " VALUES(";
		reset($value);
		while(list($key, $val) = each($value))
		{
			$qry_pre.= $key.",";
			$qry_post.= "'".addslashes($val)."',";
		}
		$qry_pre.= "datetime";	// 자료수신일자 기록용 필드 추가
		$qry_post.= "now()";	// 자료수신일자 : 데이터 수신시점
		$qry = $qry_pre.")".$qry_post.")";

		if( !(mysql_query($qry)) )	// DB처리 에러 발생시
		{
			//DB저장 불가시에는 파일로 별도 기록하여 DB 입력에러 사유를 확인토록 함
			$body = "[".date("Y-m-d :h:i:s A")."] 결제에러 (oid : ".$value[oid].") ".$qry;
			write_log("./write_failure.log",$body);

			return false;	// DB처리에 대한 결과 반환
		}
		else
		{
			return true;
		}
	}
}


function write_hasherr($value)
{
	write_log("./write_hasherr.log", $value);
	return true;
}

function write_log($file, $noti)
{
	$fp = fopen($file, "a+");
	ob_start();
	print_r($noti);
	$msg = ob_get_contents();
	ob_end_clean();
	fwrite($fp, $msg);
	fclose($fp);
}

function get_param($name)
{
	global $HTTP_POST_VARS, $HTTP_GET_VARS;
	if (!isset($HTTP_POST_VARS[$name]) || $HTTP_POST_VARS[$name] == "")
	{
		if(!isset($HTTP_GET_VARS[$name]) || $HTTP_GET_VARS[$name] == "")
		{
			return false;
		}
		else
		{
			return $HTTP_GET_VARS[$name];
		}
	}
	return $HTTP_POST_VARS[$name];
}
//====================================SHOP관련=================================================
function get_shop()
{
	$sql = "select * from g4_shop order by idx desc limit 1";
	$rst = mysql_query($sql);
	$shop = mysql_fetch_array($rst);
	return $shop;
}

function get_goods($GCODE)
{
	global $g4;

	$shop = get_shop();
	$goods_dir = $g4[path]."/data/goods/";

	if($GCODE!="")
	{
		$row = mysql_fetch_array(mysql_query("select * from g4_goods where g_code = '".$GCODE."' limit 1"));

		if($row[idx]!="")
		{
			$row[href] = $g4[path]."/shop/goods.php?GCODE=".$row[g_code];

			for($i=1;$i<=3;$i++)
			{
				if($row["g_img".$i]!="")
				{
					$row["img".$i] = "<span style='padding:1px;width:".$i."00px;height:".$i."00px;border:solid 1px #CCCCCC;cursor:pointer' onclick=\"";
					if($i < 2)
					{
						$row["img".$i].= "location.href='".$row[href]."';";
					}
					else
					{
						if($row[g_img3]!="")
						{
							$tmpSize = getimagesize($goods_dir.$row[g_img3]);
							$row["img".$i].= "ShowImg('".$goods_dir.$row[g_img3]."','".$tmpSize[0]."','".$tmpSize[1]."');";
						}
						else
						{
							$row["img".$i].= "return false;";
						}

					}
					$row["img".$i].= "\"><img src='".$goods_dir.$row["g_img".$i]."' border='0'></span>";
				}
				else
				{
					$row["img".$i] = "<span style='padding:1px;width:".$i."00px;height:".$i."00px;border:solid 1px #CCCCCC;cursor:pointer;' onclick=\"location.href='".$row[href]."';\"><table cellpadding='0' cllspacing='0' border='0' width='100%' height='".$i."00'><tr><td align='center'>No image!!</td></tr></table></span>";
				}
			}

			$row[tranc] = get_tranc($row[g_tranc]);

			$row[content] = stripslashes($row[g_content]);

			if($row[g_cnt] > 0)
			{
				$row[cnt] = number_format($row[g_cnt])."EA";
				if($row[g_min] > 0 || $row[g_max] > 0)
				{
					$row[cnt].= "(";
					if($row[g_min] > 0)
					{
						$row[cnt].= "최소구매 : ".$row[g_min]."EA";
					}
					$row[cnt].= "&nbsp;";
					if($row[g_max] > 0)
					{
						$row[cnt].= "최대구매 : ".$row[g_max]."EA";
					}
					$row[cnt].= ")";
				}
			}
			else
			{
				$row[cnt] = "<span style='color:red'>재고없음</span>";
			}

			if(trim($row[g_option])!="")
			{
				$row[opt] = "<span style='color:#0000FF;font-family:'>[옵션]</span>";
				$row[addcart] = "alert('옵션이 있는 상품입니다. 옵션을 선택하세요.');location.href='".$g4[path]."/shop/goods.php?GCODE=".$row[g_code]."';";
				$row[direct] = "alert('옵션이 있는 상품입니다. 옵션을 선택하세요.');location.href='".$g4[path]."/shop/goods.php?GCODE=".$row[g_code]."';";
			}
			else
			{
				$row[addcart] = "Cart('add','".$row[g_code]."','','');";
				$row[direct] = "DirectBuy('add','".$row[g_code]."','','');";
			}

			return $row;
		}
		else
		{
			return "";
		}
	}
	else
	{
		return "";
	}
}


function get_tranc($Str)
{
	$shop = get_shop();

	$Tranc = "";
	switch($Str)
	{
		case "Y":{$Tranc="유료(".number_format($shop[tranc_if])."원 이상 구매시 무료)";break;}
		case "N":{$Tranc="무료";break;}
		case "C":{$Tranc="착불";break;}
		default:{$Tranc="";}
	}

	return $Tranc;
}

function get_tranc2($Str)
{
	$shop = get_shop();

	$Tranc = "";
	switch($Str)
	{
		case "Y":{$Tranc="유료";break;}
		case "N":{$Tranc="무료";break;}
		case "C":{$Tranc="착불";break;}
		default:{$Tranc="";}
	}

	return $Tranc;
}

function get_category($CODE)
{
	if($CODE!="")
	{
		$sql = "select * from g4_category where c_code = '".$CODE."' limit 1";
		$rst = mysql_query($sql);
		$row = mysql_fetch_array($rst);
		return $row;
	}
	else
	{
		return "";
	}
}

function put_hit($GCODE)
{
	if($GCODE!="")
	{
		$sql = "update g4_goods set g_hit = g_hit +1 where g_code = '".$GCODE."' limit 1";
		@mysql_query($sql);
	}
}



function setCart($NAME,$MOD,$GCODE,$CNT,$GOPTION)
{
	global $g4;

	$continu = "TRUE";
	$alert = "";

	if($GCODE!="")
	{

		$goods = get_goods($GCODE);

		if($goods[g_cnt] > 0)
		{
			$tmpCart = $_SESSION[$NAME];
			$FullCode = $GCODE."OP".$GOPTION;
			
			if($tmpCart!="")
			{
				$tmpRecord = array();
				$tmpValue = explode("/",$tmpCart);

				if(!ereg($FullCode,$tmpCart))
				{
					$tmpRecord = $tmpValue;

					if($goods[g_min] > 0)
					{
						$tmpRecord[] = $FullCode."|".$goods[g_min];	
					}
					else
					{
						$tmpRecord[] = $FullCode."|1";	
					}
				}
				else
				{
					for($i=0;$i<count($tmpValue);$i++)
					{
						$tmpField = explode("|",$tmpValue[$i]);
						if($tmpField[0] == $FullCode)
						{
							if($MOD == "add")
							{
								if($goods[g_max]!=0 && $goods[g_max] <= $tmpField[1])
								{
									$continu = "FAIL";
									$alert = "최대구매수량을 초과하실 수 없습니다.";
								}
								else
								{
									$tmpField[1] = $tmpField[1]+1;
								}
							}
							elseif($MOD == "sub")
							{
								if($goods[g_min]!=0 && $goods[g_min] >= $tmpField[1])
								{
									$continu = "FAIL";
									$alert = "최소구매수량 이상 구매하셔야 합니다.";
								}
								else
								{
									$tmpField[1] = $tmpField[1]-1;
								}
							}
							elseif($MOD == "edit")
							{
								$tmpField[1] = $CNT;
							}
							elseif($MOD == "del")
							{
								$tmpField[1] = "0";
							}
							
						}

						if($tmpField[1] != "0")
						{
							$tmpValue[$i] = $tmpField[0]."|".$tmpField[1];
							$tmpRecord[] = $tmpValue[$i];
						}
					}
				}
			}
			else
			{
				if($goods[g_min] > 0)
				{
					$tmpRecord = array($FullCode."|".$goods[g_min]);
				}
				else
				{
					$tmpRecord = array($FullCode."|1");
				}
			}

		}
		else
		{
			$continu = "FAIL";
			$alert = "재고가 없습니다.";
		}
	}
	else
	{
		$continu = "FAIL";
		$alert = "상품코드가 없습니다.";
	}

	if($continu == "TRUE")
	{
		$sessionCart = implode("/",$tmpRecord);
		$_SESSION[$NAME] = $sessionCart;
		return $continu;
	}
	else
	{
		return $alert;
	}

}

function get_paymethod($STR)
{
	switch($STR)
	{
		case "card":{return "신용카드";exit;}
		case "iche":{return "자동이체";exit;}
		case "hp":{return "휴대폰결제";exit;}
		case "ebank":{return "가상계좌";exit;}
		case "bank":{return "무통장";exit;}
		default:{return "";}
	}
}

function get_status($STR)
{
	switch($STR)
	{
		case "1":{return "<span style='color:#666666'>입금대기</span>";exit;}
		case "2":{return "<span style='color:#009900'>입금확인</span>";exit;}
		case "3":{return "<span style='color:#0000FF'>배송준비중</span>";exit;}
		case "4":{return "<span style='color:#000066'>배송중</span>";exit;}
		case "5":{return "<span style='color:#999900'>완료</span>";exit;}
		case "6":{return "<span style='color:#FF0000'>취소</span>";exit;}
		case "7":{return "<span style='color:#FF00FF'>교환</span>";exit;}
		case "8":{return "<span style='color:#FF00FF'>반품</span>";exit;}
		default:{return "<span style='color:#AAAAAA'>진행중</span>";}
	}
}

function get_option($STR,$OPT)
{
	$sOpt =  $OPT - 1;
	$tmp_option = explode("[RECORD]",$STR);
	$return = explode("[FIELD]",$tmp_option[$sOpt]);
	return $return;
}
?>